import { getRoutes } from '@/api/sys-role';
import { ElMessage } from 'element-plus';
import Layout from '@/pages/login/index.vue';
import { asyncRoutes, router } from '@/router';
import { RouteRecordRaw } from 'vue-router';
const _modules = import.meta.glob('@/pages/**/*.vue');
console.log(_modules);
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles: any, route: any) {
    if (route.meta && route.meta.roles) {
        return roles.some((role: any) => route.meta.roles.includes(role));
    } else {
        return true;
    }
}

/**
 * Use names to determine if the current user has permission
 * @param names
 * @param route
 */
function hasPathPermission(paths: any, route: any) {
    if (route.path) {
        return paths.some((path: any) => route.path === path.path);
    } else {
        return true;
    }
}

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes: any, data: any) {
    data.forEach((item: any) => {
        // console.log(
        //     'ddd',
        //     `/src/pages${item.component}.vue`,
        //     _modules[`/src/pages${item.component}.vue`]
        // );
        const menu = {
            path: item.path,
            component: () => _modules[`/src/pages${item.component}.vue`],
            children: [],
            name: item.menuName,
            meta: {
                title: item.title,
                icon: item.icon,
                noCache: item.noCache,
            },
        };
        if (item.children) {
            generaMenu(menu.children, item.children);
        }
        routes.push(menu);
    });
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes: any, roles: any) {
    const res: any[] = [];

    routes.forEach((route: any) => {
        const tmp = { ...route };
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles);
            }
            res.push(tmp);
        }
    });

    return res;
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param components
 */
export function filterAsyncPathRoutes(routes: any, paths: string) {
    const res: any[] = [];

    routes.forEach((route: any) => {
        const tmp = { ...route };
        if (hasPathPermission(paths, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncPathRoutes(tmp.children, paths);
            }
            res.push(tmp);
        }
    });

    return res;
}

const permission = {
    namespaced: true,
    state() {
        return {
            routes: [],
        };
    },
    mutations: {
        SET_ROUTES: (state: any, routes: any) => {
            state.routes = routes;
        },
    },

    actions: {
        generateRoutes({ commit }: any) {
            return new Promise((resolve) => {
                getRoutes().then((res: any) => {
                    if (res.code === 200) {
                        const { data } = res;
                        const list = data[0].children;
                        //获取router添加到asyncrouter中
                        generaMenu(asyncRoutes, list);
                        console.log('调整好的路由', asyncRoutes);
                        // 添加路由
                        asyncRoutes.forEach((itemRouter: RouteRecordRaw) => {
                            router.addRoute('layout', itemRouter);
                        });
                        // router.addRoute('layout', {
                        //     path: '/vip',
                        //     component: () => import('@/pages/vip/index.vue'),
                        // });
                        // router.addRoute('layout', {
                        //     path: '/balance',
                        //     component: () =>
                        //         import('@/pages/balance/index.vue'),
                        // });
                        commit('SET_ROUTES', list);
                        resolve(list);
                    } else {
                        ElMessage.error('菜单数据获取异常');
                    }
                });
            });
        },
    },
};

export default permission;
